package com.bizdk.fastfx.fxsupport;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.util.Callback;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * fxml的加载工具类
 */
public class FxmlViewLoader {
    private static Map<String, Parent> cacheMap = new HashMap<>();

    public static <T extends JavaFxController> Parent load(FxmlView fxmlView) {
        try (InputStream fxmlStream = FxmlViewLoader.class.getResourceAsStream(fxmlView.value())) {
            FXMLLoader loader = new FXMLLoader();

            //loader.setResources(ResourceBundle.getBundle(fxmlView.bundle()));
            loader.setLocation(FxmlViewLoader.class.getResource(fxmlView.value()));
            loader.setControllerFactory(new Callback<Class<?>, Object>() {
                @Override
                public Object call(Class<?> controllerClass) {
                    try {
                        return SpringContextHolder.getBean(controllerClass);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            Parent parent = loader.load(fxmlStream);
            T controller = loader.getController();
            if (controller != null) {
                controller.initialize(FxmlViewLoader.class.getResource(fxmlView.value()), loader.getResources());
            }
            return parent;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
